package cn.wolfcode.luowowo.conmment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.conmment.repository.StrategyCommentRepository;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repository; // CRUD

    @Autowired
    private MongoTemplate template; //底层， 高级查询


    @Override
    public void save(StrategyComment comment) {
        repository.save(comment);
    }


    //评论
    @Override
    public Page query(StrategyCommentQuery qo) {

        Query query = new Query();
        //查询条件
        if (qo.getDetailId()!=-1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }

        //查总数  count
        long total = template.count(query, StrategyComment.class);

        if (total==0){
            return Page.empty();
        }

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(pageable);

        //查当前显示数据
        List<StrategyComment> list = template.find(query, StrategyComment.class);

        return new PageImpl(list,pageable,total);

    }



    //点赞
    @Override
    public void commentThumbUp(String toid, Long fromid) {

        Optional<StrategyComment> op = repository.findById(toid);

        StrategyComment comment = op.get();

        List<Long> thumbuplist = comment.getThumbuplist();
        //如果没有，则点赞+1
        if (!thumbuplist.contains(fromid)){
            int thumbupnum = comment.getThumbupnum();
            thumbupnum = thumbupnum +1;
            comment.setThumbupnum(thumbupnum);
            //把用户id存到点赞集合里
            thumbuplist.add(fromid);
        }else {
            int thumbupnum = comment.getThumbupnum();
            thumbupnum = thumbupnum -1;
            comment.setThumbupnum(thumbupnum);
            //取消点赞 移除用户id
            thumbuplist.remove(fromid);
        }
        //统一更新点赞对象
        repository.save(comment);
    }
}
